package edu.unh.sustain;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import android.sax.Element;
import android.sax.EndElementListener;
import android.sax.EndTextElementListener;
import android.sax.RootElement;
import android.util.Xml;

public class NewsFeedParser {

    // names of the XML tags
    static final String DESCRIPTION = "description";
    static final String LINK        = "link";
    static final String TITLE       = "title";
    static final String ITEM        = "item";
    static final String ROOT        = "rss";
    static final String CHANNEL     = "channel";

    private final URL   feedUrl;

    public NewsFeedParser(String feedUrl) {
        try {
            this.feedUrl = new URL(feedUrl);
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
    }

    public List<Article> parse() {
        final Article currentArticle = new Article();
        final List<Article> articles = new ArrayList<Article>();
        RootElement root = new RootElement(ROOT);

        Element channel = root.getChild(CHANNEL);
        Element item = channel.getChild(ITEM);
        item.setEndElementListener(new EndElementListener() {
            public void end() {
                articles.add(currentArticle.copy());
            }
        });
        
        item.getChild(TITLE).setEndTextElementListener(
                new EndTextElementListener() {
                    public void end(String body) {
                        currentArticle.setTitle(body);
                    }
                });
        
        item.getChild(LINK).setEndTextElementListener(
                new EndTextElementListener() {
                    public void end(String body) {
                        try {
                            currentArticle.setLink(body);
                        } catch (MalformedURLException e) {
                            // TODO Auto-generated catch block
                        }
                    }
                });
        
        item.getChild(DESCRIPTION).setEndTextElementListener(
                new EndTextElementListener() {
                    public void end(String body) {
                        currentArticle.setDescription(body);
                    }
                });
        
        try {
            Xml.parse(this.getInputStream(), Xml.Encoding.UTF_8,
                    root.getContentHandler());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return articles;
    }

    private InputStream getInputStream() {
        try {
            return feedUrl.openConnection().getInputStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
